package com.mmall.security;

import com.mmall.model.SysUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Resource;
import java.util.Collection;


public class MyAuthenticationProvider implements AuthenticationProvider {

    public MyDetailsService getMyDetailsService() {
        return myDetailsService;
    }

    public void setMyDetailsService(MyDetailsService myDetailsService) {
        this.myDetailsService = myDetailsService;
    }

    @Resource
    private MyDetailsService myDetailsService;

    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication){
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        SysUser user = (SysUser) myDetailsService.loadUserByUsername(username);
        if(user == null){
            throw new BadCredentialsException("Username not found.");
        }
        String encryData = MD5Utils.encrypt(password);
        //加密过程在这里体现
        if (!encryData.equals(user.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }
        System.out.println(user.getAuthorities().size()+"------------");
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, password, authorities));
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}

